﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Web.UI;

namespace Foothill.Service.Validation
{
    public class HtmlSanitizer : Page, IHtmlSanitizer
    {
        private string[] _whiteList;
        
        public string SanitizeHtmlText(string html, string[] whiteList)
        {
            HtmlDocument htmlDoc = new HtmlDocument();

            htmlDoc.LoadHtml(html);
            HtmlNode rootNode = htmlDoc.DocumentNode;

            _whiteList = whiteList;

            CleanHtmlNode(rootNode);

            return rootNode.InnerHtml;
        }

        private void CleanHtmlNode(HtmlNode htmlNode)
        {
            if (htmlNode.NodeType == HtmlNodeType.Element)
            {
                if (!_whiteList.Contains(htmlNode.Name))
                {
                    // unsafe element, replace it with a safe tag, also encode its inner html
                    htmlNode.Remove();
                    
                    //htmlNode.Name = "div";
                    //htmlNode.InnerHtml = Server.HtmlEncode(htmlNode.InnerHtml);
                    return;
                }
            }

            if (htmlNode.HasChildNodes)
            {
                CleanChildNodes(htmlNode);
            }
        }

        private void CleanChildNodes(HtmlNode htmlNode)
        {
            for (int i = 0; i < htmlNode.ChildNodes.Count; ++i)
            {
                CleanHtmlNode(htmlNode.ChildNodes[i]);
            }
        }
    }
}
